<template>
  <div :key="vueRest" class="addBrand-container">
    <div :key="restKey" class="container">
      <el-form
        ref="ruleForm"
        :model="ruleForm"
        :rules="rules"
        :inline="true"
        label-width="180px"
        class="demo-ruleForm"
      >
        <div>
          <el-form-item label="中药名称:" prop="name">
            <el-input
              v-model="ruleForm.name"
              placeholder="请填写中药名称"
              maxlength="20"
            />
          </el-form-item>
          <el-form-item label="分类:" prop="categoryId">
            <el-select
              v-model="ruleForm.categoryId"
              placeholder="请选择分类"
            >
              <el-option
                v-for="(item, index) in CategoryList"
                :key="index"
                :label="item.name"
                :value="item.id"
              />

            </el-select>
          </el-form-item>
        </div>
        <div>
          <el-form-item label="中药价格:" prop="price">
            <el-input v-model="ruleForm.price" placeholder="请设置中药价格" />
          </el-form-item>
        </div>
        <div>
          <el-form-item label="中药图片:" prop="image">
            <image-upload :prop-image-url="imageUrl" @imageChange="imageChange">
              图片大小不超过2M<br />仅能上传 PNG JPEG JPG类型图片<br />建议上传200*200或300*300尺寸的图片
            </image-upload>
          </el-form-item>
        </div>
        <div class="address">
          <el-form-item label="中药描述:" prop="region">
            <el-input
              v-model="ruleForm.description"
              type="textarea"
              :rows="3"
              maxlength="200"
              placeholder="中药描述，最长200字"
            />
          </el-form-item>
        </div>
        <div class="subBox address">
          <el-button @click="() => $router.back()"> 取消 </el-button>
          <el-button
            type="primary"
            :class="{ continue: actionType === 'add' }"
            @click="submitForm('ruleForm')"
          >
            保存
          </el-button>
          <el-button
            v-if="actionType == 'add'"
            type="primary"
            @click="submitForm('ruleForm', 'goAnd')"
          >
            保存并继续添加
          </el-button>
        </div>
      </el-form>
    </div>
  </div>
</template>

<script>
import { Component, Vue, Watch } from 'vue-property-decorator'
import HeadLable from '@/components/HeadLable/index.vue'
import SelectInput from './components/SelectInput.vue'
import ImageUpload from '@/components/ImgUpload/index.vue'
import {
  queryChineseMedicineById,
  addChineseMedicine,
  editChineseMedicine,
  ChineseMedicineCategoryList,
} from '@/api/chinese_medicine'
import { getToken } from '@/utils/cookies'
@Component({
  name: 'addMedicineShop',
  components: {
    HeadLable,
    SelectInput,
    ImageUpload,
  },
})
export default class extends Vue {
  restKey = 0
  textarea = ''
  value = ''
  imageUrl = ''
  actionType = ''
  CategoryList = []
  vueRest = '1'
  index = 0
  inputStyle = { flex: 1 }
  headers = {
    token: getToken(),
  }
  ruleForm = {
    name: '',
    id: '',
    price: '',
    code: '',
    image: '',
    description: '',
    status: true,
    categoryId: '',
  }

  get rules() {
    return {
      name: [
        {
          required: true,
          validator: (rule, value, callback) => {
            if (!value) {
              callback(new Error('请输入中药名称'))
            } else {
              const reg = /^([A-Za-z0-9/*\[\]\+\*\.\u4e00-\u9fa5]){2,50}$/
              if (!reg.test(value)) {
                callback(new Error('中药名称输入不符，请输入2-20个字符'))
              } else {
                callback()
              }
            }
          },
          trigger: 'blur',
        },
      ],
      categoryId: [
        { required: true, message: '请选择分类', trigger: 'change' },
      ],
      image: {
        required: true,
        message: '中药图片不能为空',
      },
      price: [
        {
          required: true,
          validator: (rules, value, callback) => {
            const reg = /^([1-9]\d{0,5}|0)(\.\d{1,2})?$/
            if (!reg.test(value) || Number(value) <= 0) {
              callback(
                new Error(
                  '中药价格格式有误，请输入大于零且最多保留两位小数的金额'
                )
              )
            } else {
              callback()
            }
          },
          trigger: 'blur',
        },
      ],
      code: [{ required: true, message: '请填写商品码', trigger: 'blur' }],
    }
  }

  created() {
    this.getCategoryList()
    this.actionType = this.$route.query.id ? 'edit' : 'add'
    if (this.$route.query.id) {
      this.init()
    }
  }

  mounted() {
  }

  async init() {
    queryChineseMedicineById(this.$route.query.id).then((res) => {
      if (res && res.data && res.data.code === 1) {
        this.ruleForm = { ...res.data.data }
        this.ruleForm.price = String(res.data.data.price)
        this.ruleForm.status = res.data.data.status == '1'
        let arr = []
        this.imageUrl = res.data.data.image
        console.log("imageUrl=",res.data.image);
      } else {
        this.$message.error(res.data.msg)
      }
    })
  }

  
  getCategoryList() {
    console.log("res")
    ChineseMedicineCategoryList({ type: 1 }).then((res) => {
      if (res.data.code === 1) {
        console.log("categoryRes",res);
        this.CategoryList = res && res.data && res.data.data
      } else {
      
        this.$message.error(res.data.msg)
      }
    }).catch(err=>{
      console.log('error',err)
    })
  }

  submitForm(formName, st) {
    this.$refs[formName].validate((valid) => {
      console.log(valid, 'valid')
      if (valid) {
        if (!this.ruleForm.image) return this.$message.error('中药图片不能为空')
        let params = { ...this.ruleForm }
        params.status =
          this.actionType === 'add' ? 0 : this.ruleForm.status ? 1 : 0
        params.categoryId = this.ruleForm.categoryId
        console.log(this.ruleForm.categoryId)
        if (this.actionType == 'add') {
          delete params.id
          addChineseMedicine(params)
            .then((res) => {
              if (res.data.code === 1) {
                this.$message.success('中药添加成功！')
                if (!st) {
                  this.$router.push({ path: '/chinesemedicine' })
                } else {
                  this.imageUrl = ''
                  this.ruleForm = {
                    name: '',
                    id: '',
                    price: '',
                    code: '',
                    image: '',
                    description: '',
                    status: true,
                    categoryId: '',
                  }
                  this.restKey++
                }
              } else {
                this.$message.error(res.data.desc || res.data.msg)
              }
            })
            .catch((err) => {
              this.$message.error('请求出错了：' + err.message)
            })
        } else {
          delete params.createTime
          delete params.updateTime
          editChineseMedicine(params)
            .then((res) => {
              if (res && res.data && res.data.code === 1) {
                this.$router.push({ path: '/chinesemedicine' })
                this.$message.success('中药修改成功！')
              } else {
                this.$message.error(res.data.desc || res.data.msg)
              }
            })
            .catch((err) => {
              this.$message.error('请求出错了：' + err.message)
            })
        }
      } else {
        return false
      }
    })
  }

  imageChange(value) {
    this.ruleForm.image = value
  }
}
</script>
<style lang="scss" scoped>
.addBrand-container {
  .el-form--inline .el-form-item__content {
    width: 293px;
  }

  .el-input {
    width: 350px;
  }

  .address {
    .el-form-item__content {
      width: 777px !important;
    }
  }
}
</style>
<style lang="scss" scoped>
.addBrand {
  &-container {
    margin: 30px;

    .container {
      position: relative;
      z-index: 1;
      background: #fff;
      padding: 30px;
      border-radius: 4px;
      min-height: 500px;

      .subBox {
        padding-top: 30px;
        text-align: center;
        border-top: solid 1px $gray-5;
      }
      .upload-item {
        .el-form-item__error {
          top: 90%;
        }
      }
    }
  }
}

.flavorBox {
  width: 777px;

  .addBut {
    background: #b8eefe;
    display: inline-block;
    padding: 0px 20px;
    border-radius: 3px;
    line-height: 40px;
    cursor: pointer;
    border-radius: 4px;
    color: #333333;
    font-weight: 500;
  }

  .flavor {
    border: solid 1px #dfe2e8;
    border-radius: 3px;
    padding: 15px;
    background: #fafafb;

    .title {
      color: #606168;
      .des-box {
        padding-left: 44px;
      }
    }

    .cont {
      .items {
        display: flex;
        margin: 10px 0;

        .itTit {
          width: 150px;
          margin-right: 15px;

          input {
            width: 100%;
          }
        }

        .labItems {
          flex: 1;
          display: flex;
          flex-wrap: wrap;
          border-radius: 3px;
          min-height: 39px;
          border: solid 1px #d8dde3;
          background: #fff;
          padding: 0 5px;

          span {
            display: inline-block;
            color: #b3f4ff;
            margin: 5px;
            line-height: 26px;
            padding: 0 10px;
            background: #fffbf0;
            border: 1px solid #c9ffff;
            border-radius: 4px;
            font-size: 12px;

            i {
              cursor: pointer;
              font-style: normal;
            }
          }

          .inputBox {
            display: inline-block;
            width: 100%;
            height: 36px;
            line-height: 36px;
            overflow: hidden;
          }
        }

        .delFlavor {
          display: inline-block;
          padding: 0 10px;
          color: #cbfffc;
          cursor: pointer;
        }
      }
    }
  }
}
</style>
